const path = require('path')
const fs = require('fs')
const {
  shell
} = require('electron')
const cp = require('child_process')
var parseString = require('xml2js').parseString;
let bookmarksDataCache = []

var config_file_dir = process.env['LOCALAPPDATA'] + '/Microsoft/VisualStudio/'
var config_file_name = 'ApplicationPrivateSettings.xml'

//遍历文件夹查找指定文件
function mapDir(dir, data) {
  files = fs.readdirSync(dir)
  files.forEach((filename, index) => {
    let pathname = path.join(dir, filename)
    stats = fs.statSync(pathname)
    if (stats.isDirectory()) {
      mapDir(pathname, data)
    } else if (stats.isFile()) {
      if (path.basename(pathname) == data['tofind']) {
        data['isfinded'] = true
        data['result'].push(pathname)
      }
    }
  })
  return data
}

//通过给定的目录和目录内可能存在的文件，查找出符合要求的所有文件
function getPathsWithBaseDirAndFilename(baseDir, filename) {
  env_realpath = baseDir
  let data = {
    'tofind': '',
    'result': []
  }
  data['tofind'] = filename

  regstr = '%.*%'
  reg = new RegExp(regstr)
  if (reg.test(env_realpath)) {
    mat = reg.exec(env_realpath)[0]
    matt = String(mat).substr(1, mat.length - 2)
    env_real = process.env[matt]
    env_realpath = baseDir.replace(mat, env_real)
  }

  return mapDir(env_realpath, data)
}

window.exports = {
  'liebiao': {
    mode: 'list',
    args: {

      enter: (action, callbackSetList) => {

        data = getPathsWithBaseDirAndFilename(config_file_dir, config_file_name)
        filepaths = data.result
        if (filepaths.length > 0) {

          filepaths.forEach((filename, index) => {

            var xml = fs.readFileSync(filename, 'utf-8')
            //解析获取到的xml描述文件
            parseString(xml, {
              explicitArray: false,
              ignoreAttrs: true
            }, function (_err, result) {

              collections = result.content.indexed.collection

              collections.forEach((item, index) => {

                //找到记录最近项目的位置
                if (item.value[1] == 'True') {

                  contents = item.value[0]
                  contentsObj = JSON.parse(contents)

                  contentsObj.forEach((content, index) => {

                    //解析每一条记录
                    projectPath = content.Key
                    lastAcessTime = content.Value.LastAccessed
                    //"LastAccessed": "2021-01-01T10:07:12.6728544+00:00",
                    timerStr = lastAcessTime.substr(0, lastAcessTime.indexOf('.'))
                    tempArr = timerStr.split('T')
                    newLastAcessTime = tempArr[0] + ' ' + tempArr[1]

                    //滤除已经删除的项目
                    if (fs.existsSync(projectPath)) {

                      pname = path.basename(projectPath)
                      let itemToPush = {
                        lowTitle: newLastAcessTime,
                        title: pname,
                        description: projectPath,
                        icon: 'item.png'
                      }

                      //滤除重复，确保最新更改的项目更靠前
                      for (let index = 0; index < bookmarksDataCache.length; index++) {
                        el = bookmarksDataCache[index];
                        if (el.title == pname) {

                          if (el.lowTitle < newLastAcessTime) {
                            bookmarksDataCache[index] = itemToPush
                          }
                          return true

                        }
                      }

                      //添加记录用于显示
                      bookmarksDataCache.push({
                        lowTitle: newLastAcessTime,
                        title: pname,
                        description: projectPath,
                        icon: 'item.png'
                      })

                    }
                  })

                }
              })

            });
          })

          bookmarksDataCache.sort(function (a, b) {
            return a.lowTitle < b.lowTitle ? 1 : -1
          })

          callbackSetList(bookmarksDataCache)
        }
      },
      // 子输入框内容变化时被调用 可选 (未设置则无搜索)
      search: (action, searchWord, callbackSetList) => {
        if (!searchWord) return callbackSetList()
        searchWord = searchWord.toLowerCase()
        return callbackSetList(bookmarksDataCache.filter(x => x.description.toLowerCase().includes(searchWord)))
      },
      // 用户选择列表中某个条目时被调用
      select: (action, itemData) => {
        window.utools.hideMainWindow()
        shell.openExternal(itemData.description).then(() => {
          bookmarksDataCache = []
          window.utools.outPlugin()
        })
      },
      // 子输入框为空时的占位符，默认为字符串"搜索"
      placeholder: "搜索"
    }
  }
}